package com.fita.wechat.web.controller;


import java.io.IOException;
import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import com.fita.entity.agent.Agent;
import com.fita.wechat.entity.security.Login;
import com.fita.wechat.service.AgentService;
import com.fita.wechat.web.resolver.Secure;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.WebUtils;

import com.demo2do.core.entity.exception.BusinessException;
import com.demo2do.core.entity.result.HttpResult;
import com.fita.entity.agent.AgentApply;
import com.fita.entity.principal.District;
import com.fita.wechat.Constant;
import com.fita.wechat.dto.AgentApplyRequest;
import com.fita.wechat.service.AgentApplyService;
import com.fita.wechat.service.DataService;
import com.fita.wechat.web.interceptor.Wechat;


/**
 * 
 * @author 宋剑宏
 *
 */
@Controller
public class AgentApplyController {

    private static final Logger logger = LoggerFactory.getLogger(AgentApplyController.class);
    
    private static final String OPENID_KEY = Constant.OPENID_KEY;

    @Autowired
    private AgentApplyService agentApplyService;
    
    @Autowired
    @Qualifier("dataService")
    private DataService<District> dataService;

    @Autowired
    private AgentService agentService;

    /**
     * 添加代理人信息填写页面
     * 
     * @return
     */
    @Wechat
    @RequestMapping(value = "/personal-agent-applies", method = RequestMethod.GET)
    public ModelAndView personalAgentApply(Long primaryAgentId, Long rate) {
        ModelAndView modelAndView = new ModelAndView("agent-apply/personal-agent-apply");
        List<District> district = dataService.loadAll(District.class);
        modelAndView.addObject("district", district);
        modelAndView.addObject("primaryAgentId", primaryAgentId);
        modelAndView.addObject("rate", rate);

        if (primaryAgentId != null){
            Agent primaryAgent = agentService.load(primaryAgentId);
            modelAndView.addObject("primaryAgent", primaryAgent);
        }
        return modelAndView;
    }
    
    /**
     * 添加代理人信息填写页面
     * 
     * @return
     */
    @Wechat
    @RequestMapping(value = "/company-agent-applies", method = RequestMethod.GET)
    public ModelAndView companyAgentApply(Long primaryAgentId, Long rate) {
        ModelAndView modelAndView = new ModelAndView("agent-apply/company-agent-apply");
        List<District> district = dataService.loadAll(District.class);
        modelAndView.addObject("district", district);
        modelAndView.addObject("primaryAgentId", primaryAgentId);
        modelAndView.addObject("rate", rate);

        if (primaryAgentId != null){
            Agent primaryAgent = agentService.load(primaryAgentId);
            modelAndView.addObject("primaryAgent", primaryAgent);
        }
        return modelAndView;
    }
    
    /**
     * 代理人信息结果页
     * @return
     */
    @Wechat
    @RequestMapping(value = "/agent-applies/result", method = RequestMethod.GET)
     public ModelAndView result() {
    	 ModelAndView modelAndView = new ModelAndView("agent-apply/agent-apply-result");
    	 return modelAndView;
     }
    
    /**
     * 异常返回页面
     * @return
     */
    @Wechat
    @RequestMapping(value = "/agent-applies/exception", method = RequestMethod.GET)
      public ModelAndView exception() {
    	  ModelAndView modelAndView = new ModelAndView("agent-apply-exception/agent-apply-exception");
    	  return modelAndView;
      }
    /**
     * 提交添加代理人信息
     * 
     * @return
     * @throws IOException 
     */
    @Wechat
    @RequestMapping(value = "/agent-applies", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public HttpResult submitAgentApply(@Secure Login login, AgentApplyRequest agentApplyRequest, HttpServletRequest request) throws IOException {

        HttpResult httpResult = new HttpResult();
        try {
            
            Cookie openidCookie = WebUtils.getCookie(request, OPENID_KEY);
            
            String openid = null;
            if(openidCookie != null) {
                openid = openidCookie.getValue();
                logger.info("agentApply get openidCookie: [{}]", openid);
            }
            
            agentApplyService.createAgentApply(agentApplyRequest, openid, login.getId());
            httpResult.success().message("添加成功");
            
            
        } catch (BusinessException e) {
            httpResult.fail(e.getCode()).message(e.getMessage());
            logger.error("doAagentApply occurs error: ", e);
           
        } catch (Exception e) {
            logger.error("doAagentApply occurs error: ", e);
            httpResult.fail("500").message("添加失败");
            
        }

        return httpResult;
    }

    /**
     * 根据id查询申请人信息
     * 
     * @param id
     * @return
     */
    @Wechat
    @RequestMapping(value = "/agent-applies/{id}", method = RequestMethod.GET)
    public ModelAndView agentApplyResult(@PathVariable Long id) {
        ModelAndView modelAndView = new ModelAndView("agent-apply/agent-apply-result");
        AgentApply agentApply = agentApplyService.load(id);
        modelAndView.addObject("agentApply", agentApply);
        return modelAndView;
    }
}
